﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using EuroManager.Presentation.WebPortal.GameViewer.Models;

namespace EuroManager.Presentation.WebPortal.GameViewer.Updates
{
    public class PlayerLocationUpdate : IGameUpdate
    {
        private Player player;
        private float frameTime;
        private float x1;
        private float y1;
        private float x2;
        private float y2;
        private float angle1;
        private float angle2;
        private float previousTime = -1;

        public PlayerLocationUpdate(Player player, float frameTime, float x1, float y1, float x2, float y2, float angle1, float angle2)
        {
            this.player = player;
            this.frameTime = frameTime;
            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
            this.angle1 = angle1;
            this.angle2 = angle2;
        }

        public void Perform(float elapsedTime)
        {
            if (elapsedTime != previousTime)
            {
                previousTime = elapsedTime;

                int playerFrameIndex = (int)(elapsedTime / frameTime);
                float weight = (elapsedTime - playerFrameIndex * frameTime) / frameTime;

                player.X = InterpolateLocation(x1, x2, weight);
                player.Y = InterpolateLocation(y1, y2, weight);
                player.Angle = InterpolateAngle(angle1, angle2, weight);
            }
        }

        public void Revert(float elapsedTime)
        {
            Perform(elapsedTime);
        }

        private float InterpolateLocation(float location1, float location2, float weight)
        {
            return (1 - weight) * location1 + weight * location2;
        }

        private float InterpolateAngle(float angle1, float angle2, float weight)
        {
            bool reverse = Math.Abs(angle1 - angle2) > 180;

            if (reverse)
            {
                if (angle1 < 0)
                {
                    angle1 = 360 + angle1;
                }
                else
                {
                    angle2 = 360 + angle2;
                }
            }

            float angle = (1 - weight) * angle1 + weight * angle2;
            return angle > 180 ? angle - 360 : angle;
        }
    }
}
